<script lang="ts" setup>
import { ref } from 'vue'
import {
  ArrowLeft,
  ArrowRight,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { GetData, PutDetailsRedact } from '@/api/modules/homePage.ts'

const ruleFormRef = ref<FormInstance>()

const ruleForm: any = ref({
  homeCarouselImageUrlList: [],
  qrCodeBGPicUrl: '',
  categorySwitch: 1,
  categoryPic: '',
  categoryLink: [],
  jingDianList: [],
  yuanJiangList: [],
})

// 初始表单数据
// const initialFormData = {
//   homeCarouselImageUrlList: [],
//   qrCodeBGPicUrl: '',
//   categorySwitch: 1,
//   categoryPic: '',
//   categoryLink: [],
//   jingDianList: [],
// }

// 图片上传赋值
function handleUploadSuccess(type: string, url: string, subscript: number, key: string, name?: string) {
  if (type === 'list') {
    const jian = (key === 'homeCarouselImageUrlList' || key === 'noticeList' || key === 'yuanJiangList') ? 'picUrl' : name as string
    ruleForm.value[key][subscript][jian] = url
  }
  else {
    ruleForm.value[key] = url
  }
}

// 弹窗添加
function AddNotice() {
  ruleForm.value.noticeList.push({
    id: 0,
    picUrl: '',
    linkUrl: '',
    flag: 1,
    vipLevel: '',
  })
}

// 轮播图添加
function AddCarousel() {
  ruleForm.value.homeCarouselImageUrlList.push({
    id: 0,
    picUrl: '',
    linkUrl: '',
    flag: 1,
  })
}
// 轮播图添加
function AddYuanJiang() {
  ruleForm.value.yuanJiangList.push({
    id: 0,
    picUrl: '',
    linkUrl: '',
    flag: 1,
  })
}

// tab景点添加
function AddTabScenic() {
  ruleForm.value.jingDianList.push({
    name: '',
    iconPic: '',
    detailPic: [
      '',
    ],
    shopLogo: '',
    shopName: '',
    shopAddress: '',
    shopMobile: '',
    longitude: '',
    latitude: '',
    sort: 0,
    kefuIcon: '',
    kefuLayer: '',
    sharePic: '',
    shareIntro: '',
    id: 0,
  })
}

// 弹窗删除
function DeleteNotice(index: number) {
  ElMessageBox.confirm(
    '你确定要删除这个弹窗吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      ruleForm.value.noticeList.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 轮播图删除
function DeleteCarousel(id: number, index: number) {
  // console.log(id)
  if (id === 0) {
    ruleForm.value.homeCarouselImageUrlList.splice(index, 1)
  }
  else {
    ElMessageBox.confirm(
      '你确定要删除这张轮播图吗？',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        ruleForm.value.homeCarouselImageUrlList.splice(index, 1)
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }
}

function ArrSort(state: string, index: number) {
  if (state === 'last') {
    if (index === 0) {
      return 0
    }
    else {
      const temp = ruleForm.value.jingDianList[index]
      ruleForm.value.jingDianList[index] = ruleForm.value.jingDianList[index - 1]
      ruleForm.value.jingDianList[index - 1] = temp
    }
  }
  else if (state === 'next') {
    if (index === ruleForm.value.jingDianList.length - 1) {
      return 0
    }
    else {
      const temp = ruleForm.value.jingDianList[index]
      ruleForm.value.jingDianList[index] = ruleForm.value.jingDianList[index + 1]
      ruleForm.value.jingDianList[index + 1] = temp
    }
  }
}

function DeleteTabScenic(index: number) {
  ElMessageBox.confirm(
    '你确定要删除这个景点吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      ruleForm.value.jingDianList.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      ruleForm.value.jingDianList.map((item: any, index: number) => {
        item.sort = index
        return item
      })
      // console.log(ruleForm.value)
      const params = {
        ...ruleForm.value,
      }
      // console.log(params)

      PutDetailsRedact(params).then((res: any) => {
        if (res.statusCode === 200) {
          ElMessage.success('提交成功')
        }
        else {
          ElMessage.error(`修改失败。${res.errors}`)
        }
      })
    }
    else {
      // console.log('error submit!', fields)
      ElMessage.error('请检查表单')
    }
  })
}

function SetVipLevel(index: number) {
  let indexs = 0
  ruleForm.value.noticeList.forEach((item: any) => {
    if (indexs !== index) {
      item.vipLevel = ''
    }
    indexs++
  })
  // ruleForm.value.noticeList[index].vipLevel = 100
  // console.log(ruleForm.value.noticeList[index])
}

onMounted(() => {
  GetData().then((res: any) => {
    if (res.statusCode === 200) {
      ruleForm.value = res.data
      ruleForm.value.jingDianList.sort((a: any, b: any) => {
        return a.sort - b.sort
      })
    }
    else {
      ElMessage.error(`获取信息失败。${res.errors}`)
    }
  })
})
</script>

<template>
  <div>
    <PageHeader title="首页配置" />
    <ElForm ref="ruleFormRef" label-position="top" :model="ruleForm.homeCarouselImageUrlList">
      <PageMain title="基本信息">
        <ElRow :gutter="20">
          <ElCol :md="24">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareIndexTxt" class="max-w-xs" style="max-width: 400px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="分享图">
              <ImageUpload
                height="200" width="auto" :size="1" :url="ruleForm.shareIndexPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, -1, 'shareIndexPic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="弹窗">
        <div>
          <el-button type="success" class="mb-5" @click="AddNotice">
            新增
          </el-button>
        </div>
        <el-space wrap :size="20">
          <ElRow :gutter="20">
            <ElCol v-for="(item, index) in ruleForm.noticeList" :key="item.id" :md="8" class="mb-5" style="min-width: 500px;">
              <el-card shadow="hover">
                <div style="display: flex; justify-content: space-between;">
                  <ElFormItem label="启用">
                    <el-switch v-model="item.flag" :active-value="1" :inactive-value="0" />
                  </ElFormItem>
                  <ElFormItem label="设为援疆会员弹窗">
                    <el-checkbox v-model="item.vipLevel" true-value="100" false-value="" @click="SetVipLevel(index)" />
                  </ElFormItem>
                </div>
                <ElFormItem label="图片">
                  <ImageUpload
                    height="auto" width="160" :size="1" :url="item.picUrl" :ext="['jpg', 'png']"
                    @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'noticeList')"
                  />
                </ElFormItem>
                <ElFormItem label="跳转地址">
                  <el-input v-model="item.linkUrl" class="max-w-xs" placeholder="请输入跳转地址" />
                </ElFormItem>
                <template #footer>
                  <div class="text-right">
                    <el-button type="danger" @click="DeleteNotice(index)">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-card>
            </ElCol>
          </ElRow>
        </el-space>
      </PageMain>
      <PageMain title="轮播">
        <div>
          <el-button type="success" class="mb-5" @click="AddCarousel">
            新增
          </el-button>
        </div>
        <el-space wrap :size="20">
          <ElRow :gutter="20">
            <ElCol v-for="(item, index) in ruleForm.homeCarouselImageUrlList" :key="item.id" :md="8" class="mb-5" style="min-width: 500px;">
              <el-card shadow="hover">
                <ElFormItem label="启用">
                  <el-switch v-model="item.flag" :active-value="1" :inactive-value="0" />
                </ElFormItem>
                <ElFormItem label="跳转地址">
                  <el-input v-model="item.linkUrl" class="max-w-xs" placeholder="请输入跳转地址" />
                </ElFormItem>
                <ElFormItem label="图片">
                  <ImageUpload
                    height="auto" width="160" :size="1" :url="item.picUrl" :ext="['jpg', 'png']"
                    @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'homeCarouselImageUrlList')"
                  />
                </ElFormItem>
                <template #footer>
                  <div class="text-right">
                    <el-button type="danger" @click="DeleteCarousel(item.id, index)">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-card>
            </ElCol>
          </ElRow>
        </el-space>
      </PageMain>
      <PageMain title="横幅">
        <ElRow :gutter="20">
          <ElCol :md="24" style="margin-bottom: 10px;">
            <ImageUpload
              height="200" width="auto" :size="1" :url="ruleForm.qrCodeBGPicUrl" :ext="['jpg', 'png']"
              @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, -1, 'qrCodeBGPicUrl')"
            />
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="跳转地址">
              <el-input v-model="ruleForm.qrCodeBGLink" class="max-w-xs" style="max-width: 400px;" placeholder="请输入跳转地址" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.yuanJiangList.length === 0" :md="24">
            <el-button type="success" @click="AddYuanJiang">
              新增
            </el-button>
          </ElCol>
          <ElCol v-for="(item, index) in ruleForm.yuanJiangList" :key="item.id" :md="8" class="mb-5" style="min-width: 500px;">
            <ElFormItem label="援疆Banner">
              <el-card shadow="hover">
                <ElFormItem label="启用">
                  <el-switch v-model="item.flag" :active-value="1" :inactive-value="0" />
                </ElFormItem>
                <ElFormItem label="图片">
                  <ImageUpload
                    height="auto" width="300" :size="1" :url="item.picUrl" :ext="['jpg', 'png']"
                    @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'yuanJiangList')"
                  />
                </ElFormItem>
                <ElFormItem label="跳转地址">
                  <el-input v-model="item.linkUrl" class="max-w-xs" placeholder="请输入跳转地址" />
                </ElFormItem>
              </el-card>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="Tab配置">
        <ElRow :gutter="20">
          <ElCol :md="12">
            <ElFormItem label="背景">
              <el-radio-group v-model="ruleForm.categorySwitch">
                <el-radio :value="1">
                  当前分类模式（默认）
                </el-radio>
                <el-radio :value="2">
                  景点
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem v-if="ruleForm.categorySwitch === 2" label="操作">
              <el-button @click="AddTabScenic">
                新增
              </el-button>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.categorySwitch === 1" :md="12">
            <ElFormItem label="LOGO跳转链接">
              <el-input v-model="ruleForm.categoryLink[0]" class="max-w-md" placeholder="请输入LOGO跳转链接" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.categorySwitch === 1" :md="12">
            <ElFormItem label="以油养肤跳转链接">
              <el-input v-model="ruleForm.categoryLink[1]" class="max-w-md" placeholder="请输入以油养肤跳转链接" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.categorySwitch === 1" :md="12">
            <ElFormItem label="植物精油跳转链接">
              <el-input v-model="ruleForm.categoryLink[2]" class="max-w-md" placeholder="请输入植物精油跳转链接" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.categorySwitch === 1" :md="12">
            <ElFormItem label="以油护体跳转链接">
              <el-input v-model="ruleForm.categoryLink[3]" class="max-w-md" placeholder="请输入以油护体跳转链接" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.categorySwitch === 1" :md="24">
            <ElFormItem label="背景">
              <ImageUpload
                height="200" width="auto" :size="1"
                :url="ruleForm.categoryPic" @on-success="(imgUrl: string) => handleUploadSuccess('single', imgUrl, -1, 'categoryPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-for="(item, index) in ruleForm.jingDianList" v-else :key="item.id" :md="12" class="mb-5">
            <el-card shadow="hover">
              <el-scrollbar height="500px" :noresize="true">
                <div class="card-box">
                  <ElFormItem label="店铺ID">
                    <el-input v-model="item.id" class="max-w-xs" placeholder="请输入店铺ID" disabled />
                  </elformitem>
                  <ElFormItem label="名称">
                    <el-input v-model="item.name" class="max-w-xs" placeholder="请输入名称" />
                  </elformitem>
                  <ElFormItem label="店铺名称">
                    <el-input v-model="item.shopName" class="max-w-xs" placeholder="请输入店铺名称" />
                  </elformitem>
                  <ElFormItem label="店铺地址">
                    <el-input v-model="item.shopAddress" class="max-w-xs" placeholder="请输入店铺地址" />
                  </elformitem>
                  <ElFormItem label="图标">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="item.iconPic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'jingDianList', 'iconPic')"
                    />
                  </ElFormItem>
                  <ElFormItem label="店铺Logo">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="item.shopLogo" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'jingDianList', 'shopLogo')"
                    />
                  </ElFormItem>
                  <ElFormItem label="店铺电话">
                    <el-input v-model="item.shopMobile" class="max-w-xs" placeholder="请输入店铺电话" />
                  </elformitem>
                  <ElFormItem label="经度">
                    <el-input v-model="item.longitude" class="max-w-xs" placeholder="请输入经度" />
                  </elformitem>
                  <ElFormItem label="维度">
                    <el-input v-model="item.latitude" class="max-w-xs" placeholder="请输入维度" />
                  </elformitem>
                  <ElFormItem label="分享语">
                    <el-input v-model="item.shareIntro" class="max-w-xs" placeholder="请输入分享语" />
                  </elformitem>
                  <ElFormItem label="客服图标">
                    <ImageUpload
                      height="150" width="auto" :size="5" :url="item.kefuIcon" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'jingDianList', 'kefuIcon')"
                    />
                  </ElFormItem>
                  <ElFormItem label="客服弹层">
                    <ImageUpload
                      height="150" width="auto" :size="5" :url="item.kefuLayer" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'jingDianList', 'kefuLayer')"
                    />
                  </ElFormItem>
                  <ElFormItem label="小程序卡片分享封面图" class="content">
                    <ImageUpload
                      height="150" width="auto" :size="5" :url="item.sharePic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess('list', imgUrl, index, 'jingDianList', 'sharePic')"
                    />
                  </ElFormItem>
                  <ElFormItem label="内容" class="content">
                    <ImagesUpload
                      :size="5" :max="30" :ext="['jpg', 'png']" :url="item.detailPic"
                    />
                  </ElFormItem>
                </div>
              </el-scrollbar>
              <template #footer>
                <div class="flex justify-between">
                  <el-button-group>
                    <el-button type="primary" :disabled="index === 0" :icon="ArrowLeft" @click="ArrSort('last', index)">
                      向前
                    </el-button>
                    <el-button type="primary" :disabled="index === ruleForm.jingDianList.length - 1" @click="ArrSort('next', index)">
                      向后
                      <el-icon class="el-icon--right">
                        <ArrowRight />
                      </el-icon>
                    </el-button>
                  </el-button-group>
                  <el-button type="danger" @click="DeleteTabScenic(index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 90px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style scoped>
/* stylelint-disable-next-line no-empty-source */
.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;

  .content {
    grid-column: 1 / 3;
  }
}
</style>
